package com.faker.controller;


import com.faker.core.dto.ResponseResult;
import com.faker.core.jdbc.DataSourceChange;
import com.faker.entity.SysConnection;
import com.faker.service.ConnectionManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 连接管理 控制器
 */
@RestController
@RequestMapping(value = "/connectionManager")
@Slf4j
public class ConnectionManagerController {
    @Resource
    private ConnectionManagerService connectionManagerService;

    /**
     * 测试连接
     *
     * @param sysConnection
     * @return
     */
    @PostMapping(value = "/testConnection")
    public ResponseResult testConnection(@RequestBody SysConnection sysConnection) {
        String msg = connectionManagerService.connectionTest(sysConnection);
        if (msg == null) {
            return ResponseResult.success("连接成功");
        } else {
            return ResponseResult.waring(msg);
        }
    }


    /**
     * 获取连接列表
     *
     * @return
     */
    @GetMapping(value = "/listConnection")
    public ResponseResult listConnection() {
        DataSourceChange.changeDataSource();
        List<SysConnection> list = connectionManagerService.getConnectionList();

        return ResponseResult.success(list);
    }


    /**
     * 新增连接
     *
     * @param sysConnection
     * @return
     */
    @PostMapping(value = "/insertConnection")
    public ResponseResult insertConnection(@RequestBody SysConnection sysConnection) {
        DataSourceChange.changeDataSource();
        int count = connectionManagerService.insertConnection(sysConnection);
        return count > 0 ? ResponseResult.success(count) : ResponseResult.waring(count);
    }

    /**
     * 修改连接
     *
     * @param sysConnection
     * @return
     */
    @PutMapping(value = "/updateConnection")
    public ResponseResult updateConnection(@RequestBody SysConnection sysConnection) {
        //TODO 修改连接后需要从Druid连接池中清空数据源，防止修改后连接仍然从连接池中获取，配置不生效
        DataSourceChange.changeDataSource();
        int count = connectionManagerService.updateConnection(sysConnection);
        return count > 0 ? ResponseResult.success(count) : ResponseResult.waring(count);
    }


    /**
     * 删除连接
     *
     * @param connectionId
     * @return
     */
    @DeleteMapping(value = "/deleteConnection/{connectionId}")
    public ResponseResult deleteConnection(@PathVariable Long connectionId) {
        DataSourceChange.changeDataSource();
        int count = connectionManagerService.deleteConnection(connectionId);
        return count > 0 ? ResponseResult.success(count) : ResponseResult.waring(count);
    }


}